package com.markhsiu.proxy;

import org.apache.log4j.Logger;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.ServerSocketChannel;

/**
 * Created by Mark Hsiu on 2017/8/5.
 */
public class MittyServer {

    private static final Logger logger = Logger.getLogger(MittyServer.class);
    private static final int cpu = Runtime.getRuntime().availableProcessors()/2;
    private static final int port = 8080;

    private MittyWorker[] workders;
    private MittyAcceptor acceptor;
    private volatile boolean running = false;
    private ServerSocketChannel serverChannel;

    public void start() throws IOException {
        if(running){
            throw  new RuntimeException();
        }


        try {
            serverChannel = ServerSocketChannel.open();
            serverChannel.configureBlocking(false);
            serverChannel.socket().bind(new InetSocketAddress(port));
            logger.info("server start .... ");
        } catch (IOException e) {
            e.printStackTrace();
        }

        acceptor = new MittyAcceptor(serverChannel);
        workders = new MittyWorker[cpu];
        for (int i=0;i<cpu;i++){
            workders[i] = new MittyWorker(serverChannel);
        }

        acceptor.start();
        for (MittyWorker worker : workders){
            worker.start();
        }

        running = true;
    }

    public void shutdown(){
        if(running){
            throw  new RuntimeException();
        }

        try {
            serverChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        running = false;
    }

    public static void main(String[] args) {
        MittyServer server = new MittyServer();
        try {
            server.start();
        } catch (IOException e) {
            e.printStackTrace();
            server.shutdown();
        }
    }
}
